#include "apue.h"
#include <sys/wait.h>

int main(void) {
    int n, i;
    int fd[2];
    pid_t pid;
    char line[MAXLINE];

    if (pipe(fd) < 0)
        err_sys("pipe error");
    if ((pid= fork()) < 0)
        err_sys("fork error");

    if (pid == 0) { /* child */
        close(fd[1]);
        while ((n =read(fd[0], line, MAXLINE)) > 0) {
            line[n]= 0;
            printf("receive data %d length: %s\n", n, line);
        }
        if (n < 0)
            err_sys("read error");
        else 
            printf("parent close pipe\n");

    } else {    /* parent */
        close(fd[0]);
        for (i=0; i<3; ++i) {
            if (write(fd[1], "hello world\n", 12 - i) < 0)
                err_sys("write error");
            sleep(2);
        }
        close(fd[1]);
        if (waitpid(pid, NULL, 0) < 0)
            err_sys("waitpid error");
    }
    exit(0);
}
